<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head>
    <th:block th:include="include :: header('店铺购买页面')"/>
    <style>
        /* 全局样式 */
        body {
            font-family: Arial, sans-serif;
            background-color: #f5f5f5;
        }

        /* 容器样式 */
        .container-div {
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
        }

        /* 按钮样式 */
        .btn {
            margin-right: 10px;
        }

        /* 表格样式 */
        .table-striped {
            background-color: #fff;
        }

        /* 购物车样式 */
        .panel-info {
            background-color: #d9edf7;
            border-color: #bce8f1;
        }

        /* 购物车项目样式 */
        #cart-items {
            margin-bottom: 10px;
        }
    </style>
</head>
<body class="gray-bg">
<div class="container-div">
    <div class="row">
        <div class="col-sm-12 select-table table-striped">
            <div class="btn-group-sm" id="toolbar" role="group" style="margin-top: 15px">
                <a class="btn btn-success" onclick="$.operate.addToCart()" shiro:hasPermission="system:addToCart">
                    <i class="fa fa-cart-plus"></i> 添加到购物车
                </a>
                <a class="btn btn-danger" onclick="$.operate.remove()" shiro:hasPermission="system:remove" disabled>
                    <i class="fa fa-minus"></i> 移除
                </a>
            </div>

            <div class="col-sm-12 select-table table-striped">
                <table id="bootstrap-table-dessert"></table>
            </div>
            <!-- 购物车面板 - 固定定位在底部 -->
            <div class="col-sm-12" style="padding: 15px;">
                <div class="panel panel-info">
                    <div class="panel-heading">购物车</div>
                    <div class="panel-body">
                        <p id="cart-items">当前购物车为空</p>
                        <p id="total-value">总价值：0 元</p>
                        <!-- 加入结算按钮 -->
                        <button id="settlementButton" class="btn btn-primary">结算</button>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<!-- 地址输入模态框 -->
<div class="modal fade" id="addressModal" tabindex="-1" role="dialog" aria-labelledby="addressModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
                <h4 class="modal-title" id="addressModalLabel">请输入收货地址</h4>
            </div>
            <div class="modal-body">
                <form id="addressForm">
                    <div class="form-group">
                        <label for="address">详细地址</label>
                        <textarea class="form-control" id="address" rows="3" required></textarea>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" id="confirmAddress">确认</button>
            </div>
        </div>
    </div>
</div>
<th:block th:include="include :: footer"/>
<script th:inline="javascript">
    var productStatusDatas = [[${@dict.getType('product_status')}]];
    var prefixDessert = ctx + "system/product";
    var createOrderUrl = ctx + "system/shopping/create";
    var cartMap = {};

    function updateCartItems(cartData) {
        console.log("cartData:{}", JSON.stringify(cartData))
        console.log("cartMap:{}", JSON.stringify(cartMap))
        var itemsText = '';
        var totalValue = 0;
        for (var item of cartData) {
            if (item.type === 'add') {
                if (cartMap[item.id + '_' + item.proType]) {
                    console.log("add...")
                    cartMap[item.id + '_' + item.proType].quantity++;
                } else {
                    cartMap[item.id + '_' + item.proType] = {
                        name: item.name,
                        price: item.price,
                        quantity: 1,
                        proType: item.proType
                    };
                }
            } else if (item.type === 'remove') {
                console.log("remove...")
                if (cartMap[item.id + '_' + item.proType] && cartMap[item.id + '_' + item.proType].quantity > 0) {
                    cartMap[item.id + '_' + item.proType].quantity--;
                    if (cartMap[item.id + '_' + item.proType].quantity === 0) {
                        delete cartMap[item.id + '_' + item.proType];
                    }
                }
            }
        }

        for (var itemName in cartMap) {
            console.log("itemName :", itemName);
            var item = cartMap[itemName];
            itemsText += item.name + '*' + item.quantity + ', ';
            totalValue += item.price * item.quantity;
        }

        itemsText = itemsText.slice(0, -2); // 去除最后多余的逗号和空格

        $('#cart-items').text(itemsText);
        $('#total-value').text('总价值：' + totalValue + ' 元');

        checkCartEmpty();
    }

    function createOrder(address) {
        var cartData = [];
        for (var itemName in cartMap) {
            var item = cartMap[itemName];
            cartData.push({
                id: itemName,
                proType: item.proType,
                quantity: item.quantity
            });
        }

        $.ajax({
            type: 'POST',
            url: createOrderUrl,
            dataType: 'json',
            data: JSON.stringify({
                shoppingDTOList: cartData,
                address: address
            }),
            contentType: "application/json; charset=utf-8",
            success: function (response) {
                console.log(JSON.stringify({
                    shoppingDTOList: cartData,
                    address: address
                }));
                // 弹窗提示
                alert('订单创建成功');
                // 清空购物车
                cartMap = {};
                updateCartItems([]);
            },
            error: function (error) {
                console.log(error);
                alert('订单创建失败');
            }
        });
    }


    // 为结算按钮添加点击事件
    // 为结算按钮添加点击事件
    $('#settlementButton').click(function () {
        if (Object.keys(cartMap).length === 0) {
            alert('购物车为空，请先添加商品');
            return;
        }
        $('#addressModal').modal('show');
    });

    // 确认地址按钮点击事件
    $('#confirmAddress').click(function() {
        var address = $('#address').val().trim();
        if (!address) {
            alert('请输入收货地址');
            return;
        }
        $('#addressModal').modal('hide');
        createOrder(address);
    });

    $(function () {
        var optionsDessert = {
            method: 'POST',
            url: prefixDessert + "/list",
            removeUrl: prefixDessert + "/remove",
            modalName: "二手物品",
            columns: [{
                checkbox: true
            },
                {
                    field: 'index',
                    title: '序号',
                    formatter: function (value, row, index) {
                        return index + 1;
                    }
                },
                {
                    field: 'id',
                    title: '主键'
                },
                {
                    field: 'productName',
                    title: '商品名称'
                },
                {
                    field: 'productPrice',
                    title: '售价'
                },
                {
                    field: 'productDesc',
                    title: '描述'
                },
                {
                    field: 'imgUrl',
                    title: '图片',
                    formatter: function (value, row, index) {
                        return '<img src="' + value + '" width="50" height="50">';
                    }
                },
                {
                    field: 'productStock',
                    title: '库存'
                },
                {
                    field: 'owner',
                    title: '卖家'
                },
                {
                    field: 'productStatus',
                    title: '商品状态',
                    formatter: function (value, row, index) {
                        if (value === '1') {
                            // 如果商品状态为下架，添加一个class来标识
                            return '<span class="disabled-status">' + $.table.selectDictLabel(productStatusDatas, value) + '</span>';
                        } else {
                            return $.table.selectDictLabel(productStatusDatas, value);
                        }
                    }
                },
                {
                    title: '操作',
                    align: 'center',
                    formatter: function (value, row, index) {
                        var actions = [];
                        if (row.productStatus !== 1) {
                            if (row.productStock > 0) {
                                actions.push('<a class="btn btn-success btn-xs" href="javascript:void(0)" onclick="$.operate.addToCart(\'' + row.id + '\', \'' + row.productName + '\', \'' + row.productPrice + '\',\'' + '0' + '\',\'' + row.productStock + '\')">添加到购物车</a> ');
                            } else {
                                actions.push('<a class="btn btn-success btn-xs disabled" href="javascript:void(0)">库存不足</a> ');
                            }
                        } else {
                            actions.push('<a class="btn btn-success btn-xs disabled" href="javascript:void(0)">商品已下架</a> ');
                        }
                        actions.push('<a class="btn btn-danger btn-xs" href="javascript:void(0)" onclick="$.operate.remove(\'' + row.id + '\', \'' + '0' + '\')" ' + (!cartMap[row.productName] ? 'disabled="disabled"' : '') + '>移除</a>');
                        return actions.join('');
                    }
                }]
        };
        $('#bootstrap-table-dessert').bootstrapTable(optionsDessert);
    });

    // 添加到购物车的操作函数
    $.operate.addToCart = function (id, name, price, proType,quantity) {
        if (cartMap[id + '_' + proType] && cartMap[id + '_' + proType].quantity >= quantity) {
            alert('该商品已达到最大购买数量');
            return;
        }
        updateCartItems([{id: id, name: name, price: price, type: "add", proType: proType}]);
    };

    // 移除的操作函数
    $.operate.remove = function (id, proType) {
        console.log("移除购物车 :", id);
        // 这里实现移除的逻辑
        updateCartItems([{id: id, type: "remove", proType: proType}]);
    };


    // 检查购物车是否为空，并相应地设置结算按钮的状态
    function checkCartEmpty() {
        if (Object.keys(cartMap).length === 0) {
            $('#settlementButton').prop('disabled', true);
        } else {
            $('#settlementButton').prop('disabled', false);
        }
    }

    // 初始化时检查购物车状态
    checkCartEmpty();
    // 监听购物车变化
    $(document).on('click', '.btn-success', function () {
        if (Object.keys(cartMap).length > 0) {
            $('#settlementButton').prop('disabled', false);
        }
    });

    $(document).on('click', '.btn-danger', function () {
        if (Object.keys(cartMap).length === 0) {
            $('#settlementButton').prop('disabled', true);
        }
    });

</script>
</body>
</html>